<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms 
of the GNU General Public License as published by the Free Software Foundation; either 
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; 
if not, write to the 
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	VALIDATEINPUT class.
*
*	Validate input for new/edit resources
*****/
class VALIDATEINPUT
{
// Constructor
	function VALIDATEINPUT($db, $vars, $parentObject = FALSE)
	{
		$this->db = $db;
		$this->vars = $vars;
		if(!$parentObject) // Validating from RESOURCEEDIT when converting a resource type
		{
			include_once("core/resource/RESOURCEEDIT.php");
			$parentObject = new RESOURCEEDIT($this->db, $this->vars);
		}
		$this->parentObject = $parentObject;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/MISC.php");
		include_once("core/html/FORM.php");
		include_once("core/html/TABLE.php");
		include_once("core/resource/RESOURCEMAP.php");
		$this->map = new RESOURCEMAP();
	}
// Input from stage 1 prior to stage 2
	function stage1($edit = FALSE)
	{
		if(array_key_exists('resource_typeConvert', $this->vars))
			$type = $this->vars['resource_typeConvert'];
		else
			$type = $this->vars['resource_type'];
// preliminary write to session
		$this->writeSession();
// If title has been edited to remove the noSort value, remove it from the session so that it's not written back to the database
		$title = trim($this->vars['resource_title']);
		if(array_key_exists('resource_title', $this->vars) && $title)
		{
			$oldTitle = $this->session->getVar("resource_fullTitle");
			if($title != $oldTitle)
			{
				$this->session->delVar('resource_noSort');
				$this->session->delVar('resource_fullTitle');
			}
		}
		include_once("core/messages/LANGUAGE.php");
		$noSortArray = LANGUAGE::noSort();
		$foundNoSort = FALSE;
		foreach($noSortArray as $pattern)
		{
			if(preg_match("/^($pattern)\s(.*)/i", $title, $matches))
			{
				$this->session->setVar('resource_noSort', $matches[1]);
				$this->session->setVar('resource_title', $matches[2]);
				$foundNoSort = TRUE;
				break;
			}
		}
		if(!$foundNoSort)
			$this->session->delVar('resource_noSort');
		if(!$this->vars['resource_type'] || !trim($this->vars['resource_title']) || 
			(trim($this->vars['resource_title']) == '{}'))
			$this->badInput($this->errors->text("inputError", "missing"));
// book_chapter: 'title' is 'chapter' and must be numeric
// NB - ctype_digit() not available in all PHP configurations (debian and gentoo for example)
		if(($type == 'book_chapter') && preg_match("/\D/", trim($this->vars['resource_title'])))
			$this->badInput($this->errors->text("inputError", "chapterNotNumeric"));
		if(!array_key_exists("confirmDuplication", $this->vars) || !$this->vars['confirmDuplication'])
			$this->checkDuplication($edit);
		return $this->triage();
	}
// If adding a new resource to a collection
	function stage1a()
	{
// preliminary write to session
		$this->writeSession();
//		if(!array_key_exists('resource_collectionId', $this->vars) || !$this->vars['resource_collectionId'])
//			$this->badInput($this->errors->text("inputError", "missing"), "stage1a");
		return $this->triage();
	}
// Input from stage 2 prior to stage 3
	function stage2($edit = FALSE)
	{
// preliminary write to session
		$this->writeSession();
		for($i = 1; $i < 6; $i++)
		{
			$input = "resource_num_creator" . $i;
			if(isset($this->vars[$input]) && trim($this->vars[$input]) && 
				preg_match("/\D/", trim($this->vars[$input])))
				$this->badInput($this->errors->text("inputError", "invalid"), "stage2");
		}
		return $this->triage();
	}
// if this title and type already exist, ask for confirmation before proceeding.
// NB book_chapter.  title is the chapter no. so don't check for duplicates.
	function checkDuplication($edit)
	{
		if(array_key_exists('resource_typeConvert', $this->vars))
			$type = $this->vars['resource_typeConvert'];
		else
			$type = $this->vars['resource_type'];
		if($type == 'book_chapter')
			return;
		include_once("core/sql/STATEMENTS.php");
		$stmt = new STATEMENTS($this->db);
		$concat = $this->db->concat(
				array(
				"CASE WHEN " . $this->db->formatField('noSort') . " IS NULL" . 
				" THEN " . $this->db->tidyInputNoTrim('') . 
				" ELSE " . 
					$this->db->concat(array($this->db->formatField('noSort'), 
					$this->db->tidyInputNoTrim(' '))) . 
				" END", 
				$this->db->formatField('title')
				));
		$condition = " WHERE $concat=" . 
			$this->db->tidyInput($this->vars['resource_title']) . 
			" AND " . $this->db->formatField('WKX_resource.type') . "=" . $this->db->tidyInput($type);
		if(array_key_exists('resource_subtitle', $this->vars) && trim($this->vars['resource_subtitle']))
			$condition .= " AND " . $this->db->formatField('WKX_resource.subtitle') . "=" . 
			$this->db->tidyInput($this->vars['resource_subtitle']);
		$recordset = $this->db->select(array("WKX_resource"), $stmt->listFields(), 
			$stmt->selectJoin() . $condition);
		if($this->db->numRows($recordset))
		{
			include_once("core/styles/BIBSTYLE.php");
			$bibStyle = new BIBSTYLE($this->db, "html");
			include_once("core/html/CLOSE.php");
			include_once("core/template/TEMPLATE.php");
			$template = new TEMPLATE('content');
			$pString = $this->errors->text("warning", "resourceExists");
			while($row = $this->db->loopRecordSet($recordset))
			{
				if($edit && ($row['resourceId'] == $this->session->getVar('resource_resourceId')))
					return;
				$resources[] = $bibStyle->process($row);
			}
			if(!$edit)
			{
				$template->setVar('heading', $this->messages->text("heading", "newResource"));
				$pString .= FORM::formHeader("resourceNew");
			}
// editing
			else
			{
				$template->setVar('heading', $this->messages->text("heading", "editResource"));
				$pString .= FORM::formHeader("resourceEdit");
				for($i = 1; $i < 6; $i++)
				{
					$type = "resource_numCreator" . $i;
					$pString .= FORM::hidden($type, $this->session->getVar($type));
				}
			}
			$pString .= FORM::hidden("resource_type", $this->vars['resource_type']);
			$pString .= FORM::hidden("resource_title", $this->vars['resource_title']);
			$pString .= FORM::hidden("resource_subtitle", $this->vars['resource_subtitle']);
			$pString .= FORM::hidden("method", 'stage2');
			$pString .= FORM::hidden("confirmDuplication", 'TRUE');
			$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
			$index = 0;
			foreach($resources as $resource)
			{
				$pString .= TABLE::trStart();
				$class = $index % 2 ? 'alternate2' : 'alternate1';
				$pString .= TABLE::td($resource, $class);
				$pString .= TABLE::trEnd();
				$index++;
			}
			$pString .= TABLE::tableEnd();
			$pString .= MISC::br() . "&nbsp;" . MISC::br();
			$pString .= $this->messages->text("resources", "confirm");
			$pString .= MISC::br() . "&nbsp;" . MISC::br();
			$pString .= MISC::p(FORM::formSubmit("Confirm"), FALSE, "right");
			$pString .= FORM::formEnd();
			$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
			$template->setVar('body', $pString);
			new CLOSE($this->db, $template->process());
		}
	}
// Input from stage 3 prior to stage 4
	function stage3()
	{
// peerReviewed is special case
		if(!array_key_exists('resource_peerReviewed', $this->vars))
			$this->session->delVar('resource_peerReviewed');
// preliminary write to session
		$this->writeSession();
		$type = $this->session->getVar('resource_type');
// book_chapter: 'title' is 'chapter' and must be numeric
		if(($type == 'book_chapter') && $this->session->getVar("resource_typeConvert") && 
			preg_match("/\D/", trim($this->vars['resource_title'])))
			$this->badInput($this->errors->text("inputError", "chapterNotNumeric"), 'stage3');
		if(array_key_exists("jump", $this->vars) || $this->session->getVar("resource_typeConvert"))
		{
			if(array_key_exists('resource_collection', $this->vars))
				$this->checkInputCollection($type);
			return $this->triage();
		}
		foreach($this->map->{$type}['resource_creator'] as $creatorType => $throwaway)
		{
			$input = array();
			foreach($this->vars as $key => $value)
			{
				$base = "resource_" . $creatorType . "_";
				if(preg_match("/^$base(.*)/", $key, $match))
					$input[$match[1]] = trim($value);
			}
			if(empty($input))
				continue;
// split on "_"
			foreach($input as $key => $value)
			{
				$components = explode("_", $key);
				if($value = trim($value))
					${$creatorType}[$components[0]][$components[1]] = $value;
			}
			if(empty(${$creatorType}))
				continue;
			foreach(${$creatorType} as $key => $value)
			{
				if(array_key_exists('surname', $value) && $value['surname'])
					$this->vars['resource_' . $creatorType . '_' . $key . '_id'] = FALSE;
				else if(!array_key_exists('resource_' . $creatorType . '_' . $key . '_id', $this->vars) 
					|| !$this->vars['resource_' . $creatorType . '_' . $key . '_id'] && 
					!$this->vars['resource_' . $creatorType . '_' . $key . '_surname'])
				{
					$this->vars['resource_' . $creatorType . '_' . $key . '_initials'] = FALSE;
					$this->vars['resource_' . $creatorType . '_' . $key . '_prefix'] = FALSE;
					$this->vars['resource_' . $creatorType . '_' . $key . '_firstname'] = FALSE;
					$this->vars['resource_' . $creatorType . '_' . $key . '_id'] = FALSE;
				}
				else if(array_key_exists('resource_' . $creatorType . '_' . $key . '_id', $this->vars) 
					&& !${$creatorType}[$key]['id'])
					$this->badInput($this->errors->text("inputError", "missing"), 'stage2');
// if id remains, we get rid of initials and firstname
				if(array_key_exists('resource_' . $creatorType . '_' . $key . '_id', $this->vars) && 
					$this->vars['resource_' . $creatorType . '_' . $key . '_id'])
				{
					$this->vars['resource_' . $creatorType . '_' . $key . '_initials'] = FALSE;
					$this->vars['resource_' . $creatorType . '_' . $key . '_firstname'] = FALSE;
				}
			}
		}
		$this->stage4();
		$this->stage5();
		return $this->triage();
	}
// Input from stage 4 prior to stage 5
	function stage4()
	{
		if(array_key_exists('resource_book', $this->vars) && $this->vars['resource_book'] && 
			!$this->vars['resource_bookTitle'] && ($this->vars['resource_book'] != 'IGNORE'))
		{
			$this->vars['resource_bookTitle'] = $this->vars['resource_book'];
			unset($this->vars['resource_book']);
		}
// Can't have subtitle but not title of original translated work (book and book_article only).
		if(array_key_exists('resource_transSubtitle', $this->vars) && 
			!array_key_exists('resource_transTitle', $this->vars))
			unset($this->vars['resource_transSubtitle']);
// If translated title has been edited to remove the transNoSort value, remove it from the session so that it's not written back to the database
		if(array_key_exists('resource_transTitle', $this->vars))
		{
			$title = trim($this->vars['resource_transTitle']);
			if(array_key_exists('resource_transTitle', $this->vars) && $title)
			{
				$oldTitle = $this->session->getVar("resource_fullTransTitle");
				if($title != $oldTitle)
				{
					$this->session->delVar('resource_transNoSort');
					$this->session->delVar('resource_fullTransTitle');
				}
			}
		}
// preliminary write to session
		$this->writeSession();
		if(array_key_exists('resource_transTitle', $this->vars))
		{
			include_once("core/messages/LANGUAGE.php");
			$noSortArray = LANGUAGE::noSort();
			$foundNoSort = FALSE;
			foreach($noSortArray as $pattern)
			{
				if(preg_match("/^($pattern)\s(.*)/i", $title, $matches))
				{
					$this->session->setVar('resource_transNoSort', $matches[1]);
					$this->session->setVar('resource_transTitle', $matches[2]);
					$foundNoSort = TRUE;
					break;
				}
			}
			if(!$foundNoSort)
				$this->session->delVar('resource_transNoSort');
		}
		if(array_key_exists("jump", $this->vars))
			return $this->triage();
		$type = $this->session->getVar('resource_type');
		if(!$this->session->getVar("resource_collectionId"))
		{
			foreach($this->map->{$type}['stage4'] as $key => $value)
			{
// Collection is special as there may be a pre-selected collection title being used instead
				if($key == 'collection')
				{
					if((!isset($this->vars["resource_$key"]) || !$this->vars["resource_$key"])
						&& (!isset($this->vars["resource_" . $key . "_id"]) || 
						!$this->vars["resource_" . $key . "_id"]))
						$this->badInput($this->errors->text("inputError", "missing", " (" . 
						$this->messages->text("resources", $value) . ")"), 'stage4');
				}
				else
				{
					if(!isset($this->vars["resource_$key"]) || !$this->vars["resource_$key"])
						$this->badInput($this->errors->text("inputError", "missing", " (" . 
						$this->messages->text("resources", $value) . ")"), 'stage4');
				}
			}
		}
		if($type == 'book')
		{
			$this->checkInputPublisher();
			$this->checkInputTransPublisher();
			$this->checkInputNumbers($type);
		}
		else if(($type == 'book_article') || ($type == 'book_chapter'))
		{
			if(!$this->session->getVar("resource_collectionId"))
			{
				$this->checkInputCollection($type);
				$this->checkInputPublisher();
				$this->checkInputTransPublisher();
				$this->checkInputNumbers($type);
			}
			$this->checkInputPage();
		}
		else if($type == 'journal_article')
		{
			if(!$this->session->getVar("resource_collectionId"))
				$this->checkInputCollection($type);
			$this->checkInputNumbers($type);
			$this->checkInputPage();
		}
		else if($type == 'newspaper_article')
		{
			if(!$this->session->getVar("resource_collectionId"))
				$this->checkInputCollection($type);
			$this->checkInputPage();
		}
		else if($type == 'magazine_article')
		{
			if(!$this->session->getVar("resource_collectionId"))
				$this->checkInputCollection($type);
			$this->checkDateRange($type);
			$this->checkInputPage();
		}
		else if(($type == 'web_site') || ($type == 'web_encyclopedia') || ($type == 'web_encyclopedia_article'))
			$this->checkInputWeb();
		else if($type == 'web_article')
		{
			$this->checkInputWeb();
			if(!$this->session->getVar("resource_collectionId"))
				$this->checkInputCollection($type);
			$this->checkInputNumbers($type);
			$this->checkInputPage();
		}
		else if($type == 'proceedings')
		{
			$this->checkInputPublisher();
			$this->checkDateRange($type);
		}
		else if($type == 'conference_paper')
			$this->checkInputPublisher();
		else if($type == 'proceedings_article')
		{
			if(!$this->session->getVar("resource_collectionId"))
			{
				$this->checkInputCollection($type);
				$this->checkDateRange($type);
			}
			$this->checkInputPage();
		}
		else if($type == 'thesis')
		{
			$this->checkInputThesis();
			$this->checkInputPublisher();
			$this->checkInputNumbers($type);
			$this->checkInputPage();
		}
		else if($type == 'film')
		{
			$this->checkInputPublisher();
			$this->checkInputNumbers($type);
		}
		else if($type == 'broadcast')
		{
			$this->checkInputPublisher();
			$this->checkInputNumbers($type);
			$this->checkInputYear2($type);
		}
		else if($type == 'artwork')
			$this->checkInputPublisher();
		else if($type == 'audiovisual')
		{
			$this->checkInputPublisher();
			$this->checkInputNumbers($type);
		}
		else if($type == 'software')
			$this->checkInputPublisher();
		else if($type == 'case')
		{
			$this->checkInputPublisher();
			$this->checkInputNumbers($type);
		}
		else if($type == 'legal_ruling')
		{
			$this->checkInputPublisher();
			$this->checkInputYear2($type);
			$this->checkInputNumbers($type);
		}
		else if($type == 'bill')
		{
			$this->checkInputPublisher();
			$this->checkInputNumbers($type);
			$this->checkInputPage();
		}
		else if($type == 'government_report')
		{
			$this->checkInputPublisher();
			$this->checkInputNumbers($type);
		}
		else if($type == 'report')
			$this->checkInputPublisher();
		else if($type == 'classical'); // nothing
		else if($type == 'manuscript')
			$this->checkInputNumbers($type);
		else if($type == 'map')
			$this->checkInputPublisher();
		else if($type == 'chart')
			$this->checkInputPublisher();
		else if($type == 'hearing')
		{
			$this->checkInputPublisher();
			$this->checkInputNumbers($type);
		}
		else if($type == 'database')
		{
			$this->checkInputPublisher();
			$this->checkInputWeb();
		}
		else if($type == 'statute')
			$this->checkInputPage();
		else if($type == 'patent')
		{
			$this->checkInputPublisher();
			$this->checkInputNumbers($type);
		}
		else if($type == 'personal')
			$this->checkInputNumbers($type);
		else if($type == 'music_album')
			$this->checkInputPublisher();
		else if($type == 'music_track')
		{
			if(!$this->session->getVar("resource_collectionId"))
			{
				$this->checkInputCollection($type);
				$this->checkInputPublisher();
			}
		}
		else if($type == 'music_score')
			$this->checkInputPublisher();
		else if($type == 'unpublished')
		{
			$this->checkInputPublisher();
			$this->checkInputPage($type);
		}
		else if(($type == 'miscellaneous') || ($type == 'miscellaneous_section'))
		{
			if(!$this->session->getVar("resource_collectionId"))
				$this->checkInputPublisher();
		}
//		return $this->triage();
	}
// Input from stage 5 - FINAL
	function stage5()
	{
// preliminary write to session
		$this->writeSession();
		if($this->session->getVar("resource_typeConvert"))
			return $this->triage();
		if(($this->session->getVar('resource_type') != 'web_site') && 
			($this->session->getVar('resource_type') != 'web_article') && 
			($this->session->getVar('resource_type') != 'web_encyclopedia') && 
			($this->session->getVar('resource_type') != 'web_encyclopedia_article') && 
			($this->session->getVar('resource_type') != 'database'))
		{
			if(trim($this->vars['resource_url']) == 'http://')
				$this->vars['resource_url'] = FALSE;
		}
		if(empty($this->vars['resource_group_ids']))
// force to 'General' group '1'
			$this->vars['resource_group_ids'][] = 1;
// if keyword_ids array has only the 0 => 'IGNORE' entry, set to FALSE
		if(!empty($this->vars['resource_keyword_ids']))
		{
			if((sizeof($this->vars['resource_keyword_ids']) == 1) && 
			!$this->vars['resource_keyword_ids'][0])
				$this->vars['resource_keyword_ids'] = FALSE;
		}
//		return $this->triage();
	}
// all is optional but...
	function checkInputPublisher()
	{
// if publisher name or location, remove publisher_id from input vars.
		if(trim($this->vars['resource_publisherName']))
			$this->vars['resource_publisher_id'] = FALSE;
// If publisherLocation but !publisherName, set publisherLocation to FALSE
		if(isset($this->vars['resource_publisherLocation']) && 
			!trim($this->vars['resource_publisherName']) && trim($this->vars['resource_publisherLocation']))
			$this->vars['resource_publisherLocation'] = FALSE;
	}
// all is optional but...
	function checkInputTransPublisher()
	{
// if transPublisher name or location, remove transPublisher_id from input vars.
		if(trim($this->vars['resource_transPublisherName']))
			$this->vars['resource_transPublisher_id'] = FALSE;
// If transPublisherLocation but !transPublisherName, set transPublisherLocation to FALSE
		if(isset($this->vars['resource_transPublisherLocation']) && 
			!trim($this->vars['resource_transPublisherName']) && 
			trim($this->vars['resource_transPublisherLocation']))
			$this->vars['resource_transPublisherLocation'] = FALSE;
	}
// all is optional but... miscField 1.. miscField 4 must be integers
	function checkInputNumbers($type)
	{
		$array = array("miscField1", "miscField2", "miscField3", "miscField4");
		foreach($array as $key)
		{
			if(isset($this->vars["resource_$key"]) && trim($this->vars["resource_$key"])
				&& (!is_numeric(trim($this->vars["resource_$key"])) && 
				(trim($this->vars["resource_$key"]) != $this->messages->text('misc', 'ignore'))))
				$this->badInput($this->errors->text("inputError", "nan", " (" . 
				$this->messages->text("resources", $this->map->{$type}['resource_misc'][$key]) . 
				")"), 'stage4');
		}
	}
// all is optional but...
	function checkDateRange($type)
	{
// If no start dates but only end dates, put end dates into start date fields.
		if(($type == 'magazine_article') && !trim($this->vars['resource_year1']) && 
			!trim($this->vars['resource_miscField2']) && !trim($this->vars['resource_miscField3']))
		{
			if(trim($this->vars['resource_year3']))
			{
				$this->vars['resource_year1'] = trim($this->vars['resource_year3']);
				$this->session->setVar('resource_year1', trim($this->vars['resource_year3']));
				$this->session->delVar('resource_year3');
			}
			if(trim($this->vars['resource_miscField5']))
			{
				$this->vars['resource_miscField2'] = trim($this->vars['resource_miscField5']);
				$this->session->setVar('resource_miscField2', trim($this->vars['resource_miscField5']));
				$this->session->delVar('resource_miscField5');
			}
			if(trim($this->vars['resource_miscField6']))
			{
				$this->vars['resource_miscField3'] = trim($this->vars['resource_miscField6']);
				$this->session->setVar('resource_miscField3', trim($this->vars['resource_miscField6']));
				$this->session->delVar('resource_miscField6');
			}
		}
		else if(array_key_exists('resource_year2', $this->vars) && !trim($this->vars['resource_year2']) && 
			!trim($this->vars['resource_miscField2']) && !trim($this->vars['resource_miscField3']))
		{
			if(trim($this->vars['resource_year3']))
			{
				$this->vars['resource_year2'] = trim($this->vars['resource_year3']);
				$this->session->setVar('resource_year2', trim($this->vars['resource_year3']));
				$this->session->delVar('resource_year3');
			}
			if(trim($this->vars['resource_miscField5']))
			{
				$this->vars['resource_miscField2'] = trim($this->vars['resource_miscField5']);
				$this->session->setVar('resource_miscField2', trim($this->vars['resource_miscField5']));
				$this->session->delVar('resource_miscField5');
			}
			if(trim($this->vars['resource_miscField6']))
			{
				$this->vars['resource_miscField3'] = trim($this->vars['resource_miscField6']);
				$this->session->setVar('resource_miscField3', trim($this->vars['resource_miscField6']));
				$this->session->delVar('resource_miscField6');
			}
		}
/*
// For end dates, assume similar dates to start date if some end date information missing.
// 1. Day and no more
		else if(trim($this->vars['resource_miscField5']) && !trim($this->vars['resource_miscField6']) && 
			!trim($this->vars['resource_year3']))
		{
			if(trim($this->vars['resource_miscField5']) != trim($this->vars['resource_miscField2']))
			{
				if(trim($this->vars['resource_year2']))
				{
					$this->vars['resource_year3'] = trim($this->vars['resource_year2']);
					$this->session->setVar('resource_year3', trim($this->vars['resource_year2']));
				}
				if(trim($this->vars['resource_miscField3']))
				{
					$this->vars['resource_miscField6'] = trim($this->vars['resource_miscField3']);
					$this->session->setVar('resource_miscField6', trim($this->vars['resource_miscField3']));
				}
			}
			else
				$this->session->delVar('resource_miscField5');
		}
// 2. Day + month only
		else if(trim($this->vars['resource_miscField5']) && !trim($this->vars['resource_year3']))
		{
			if(trim($this->vars['resource_year2']))
			{
				$this->vars['resource_year3'] = trim($this->vars['resource_year2']);
				$this->session->setVar('resource_year3', trim($this->vars['resource_year2']));
			}
		}
// 3. Month only
		else if(trim($this->vars['resource_miscField6']) && !trim($this->vars['resource_miscField5']) && 
			!trim($this->vars['resource_year3']))
		{
			if(trim($this->vars['resource_miscField6']) != trim($this->vars['resource_miscField3']))
			{
				if(trim($this->vars['resource_year2']))
				{
					$this->vars['resource_year3'] = trim($this->vars['resource_year2']);
					$this->session->setVar('resource_year3', trim($this->vars['resource_year2']));
				}
				if(trim($this->vars['resource_miscField2']))
				{
					$this->vars['resource_miscField5'] = trim($this->vars['resource_miscField2']);
					$this->session->setVar('resource_miscField5', trim($this->vars['resource_miscField2']));
				}
			}
			else
				$this->session->delVar('resource_miscField6');
		}
// 4. Month + year only
		else if(trim($this->vars['resource_miscField6']) && !trim($this->vars['resource_miscField5']))
		{
			if(trim($this->vars['resource_miscField2']))
			{
				$this->vars['resource_miscField5'] = trim($this->vars['resource_miscField2']);
				$this->session->setVar('resource_miscField5', trim($this->vars['resource_miscField2']));
			}
		}
// 5. Year only
		else if(trim($this->vars['resource_year3']) && !trim($this->vars['resource_miscField5']) && 
			!trim($this->vars['resource_miscField6']))
		{
			if(trim($this->vars['resource_year3']) != trim($this->vars['resource_year2']))
			{
				if(trim($this->vars['resource_miscField3']))
				{
					$this->vars['resource_miscField6'] = trim($this->vars['resource_miscField3']);
					$this->session->setVar('resource_miscField6', trim($this->vars['resource_miscField3']));
				}
				if(trim($this->vars['resource_miscField2']))
				{
					$this->vars['resource_miscField5'] = trim($this->vars['resource_miscField2']);
					$this->session->setVar('resource_miscField5', trim($this->vars['resource_miscField2']));
				}
			}
			else
				$this->session->delVar('resource_year3');
		}
// 6. Year + day only
		else if(trim($this->vars['resource_year3']) && !trim($this->vars['resource_miscField6']))
		{
			if(trim($this->vars['resource_miscField3']))
			{
				$this->vars['resource_miscField6'] = trim($this->vars['resource_miscField3']);
				$this->session->setVar('resource_miscField6', trim($this->vars['resource_miscField3']));
			}
		}
*/
	}
// all is optional but... 
	function checkInputPage()
	{
		$ps = "pageStart";
		$pe = "pageEnd";
		if(!trim($this->vars['resource_' . $ps]))
		{
			$this->vars['resource_' . $ps] = FALSE;
			$this->vars['resource_' . $pe] = FALSE;
		}
// remove pageEnd if the same as pageStart
		if(trim($this->vars['resource_' . $ps]) == trim($this->vars['resource_' . $pe]))
			$this->vars['resource_' . $pe] = FALSE;
// force lower characters in case input is roman numerals
		if(trim($this->vars['resource_' . $ps]))
			$this->session->setVar('resource_' . $ps, strtolower($this->vars['resource_' . $ps]));
		if(trim($this->vars['resource_' . $pe]))
			$this->session->setVar('resource_' . $pe, strtolower($this->vars['resource_' . $pe]));
// page start must not be greater than page end.
		if(trim($this->vars['resource_' . $ps]) && trim($this->vars['resource_' . $pe]) && 
		is_numeric(trim($this->vars['resource_' . $ps])) && 
		is_numeric(trim($this->vars['resource_' . $pe])) && 
		(trim($this->vars['resource_' . $ps]) > trim($this->vars['resource_' . $pe])))
			$this->badInput($this->errors->text("inputError", "invalid", " (" . 
			$this->messages->text("resources", "pageStart") . " > " . 
			$this->messages->text("resources", "pageEnd") . ")"), 'stage4');
	}
// all is optional but... 
	function checkInputThesis()
	{
		if($value = trim($this->vars['resource_field1']))
			$this->session->setVar('resource_field1', $value);
		if($value = trim($this->vars['resource_field2']))
			$this->session->setVar('resource_field2', $value);
// If no abstract journal input, ensure page no.s and abstract year are FALSE
		if(!$this->session->getVar("resource_collectionId"))
		{
			if(!trim($this->vars['resource_collection']) && 
				isset($this->vars['resource_collection_id']) && 
				!trim($this->vars['resource_collection_id']))
			{
				$this->vars['resource_pageStart'] = FALSE;
				$this->vars['resource_pageEnd'] = FALSE;
				$this->vars['resource_year2'] = FALSE;
				$this->vars['resource_miscField3'] = FALSE;
				$this->vars['resource_miscField4'] = FALSE;
			}
		}
	}
// all is optional but... 
	function checkInputCollection($type, $stage = 'stage4')
	{
// if no journal title, set volume and issue to false.
// type 'journal_article', newspaper_article, proceedings_article, miscellaneous_section and book_article must have a title, 
// web_article and theses types _may_ be part of a journal
		if(!trim($this->vars['resource_collection']))
		{
			if((($type == 'journal_article') || ($type == 'newspaper_article') ||
			($type == 'book_article') || ($type == 'proceedings_article') 
			 || ($type == 'miscellaneous_section')) && 
			(!array_key_exists('resource_collection_id', $this->vars) || 
			!$this->vars['resource_collection_id']))
				$this->badInput($this->errors->text("inputError", "missing", " (" . 
				$this->messages->text("resources", "collectionTitle") . ")"), $stage);
			if((!array_key_exists('resource_collection_id', $this->vars) || 
				!$this->vars['resource_collection_id']) && (
				($type == 'thesis') || ($type == 'web_article')))
			{
				$this->vars['resource_journalVolumeNumber'] = 
				$this->vars['resource_journalIssueNumber'] = FALSE;
			}
		}
		else
			$this->vars['resource_collection_id'] = FALSE;
		if(($type != 'web_article') || ($type != 'journal_article') || ($type != 'thesis'))
			return;
// issue number and no volume, set issue to false
		if(!trim($this->vars['resource_volumeNumber']) && 
		trim($this->vars['resource_issueNumber']))
			$this->vars['resource_issueNumber'] = FALSE;
	}
// Not required but, if no year, remove day and month
	function checkInputYear2()
	{
		if(isset($this->vars['resource_year2']) && !trim($this->vars['resource_year2']))
		{
			$this->session->delVar('resource_miscField2');
			$this->session->delVar('resource_miscField3');
		}
	}
// check web_article, web_site input
	function checkInputWeb()
	{
		if((trim($this->vars['resource_url']) == 'http://') || (!trim($this->vars['resource_url'])))
			$this->badInput($this->errors->text("inputError", "missing", " (" . 
			$this->messages->text("resources", "url") . ")"), 'stage4');
		if(!is_numeric(trim($this->vars['resource_miscField2'])) || (!trim($this->vars['resource_miscField2'])))
			$this->badInput($this->errors->text("inputError", "invalid", " (" . 
			$this->messages->text("resources", "day") . ")"), 'stage4');
		if(!is_numeric(trim($this->vars['resource_miscField3'])) || (!trim($this->vars['resource_miscField3'])))
			$this->badInput($this->errors->text("inputError", "invalid", " (" . 
			$this->messages->text("resources", "month") . ")"), 'stage4');
		if(!is_numeric(trim($this->vars['resource_year2'])) || 
		(!trim($this->vars['resource_year2']))
		 || (trim($this->vars['resource_year2']) < 1000))
			$this->badInput($this->errors->text("inputError", "invalid", " (" . 
			$this->messages->text("resources", "year") . ")"), 'stage4');
	}
// check newspaper_article magazine_article input
	function checkInputNewspaperDate($type)
	{
// must be valid integer or 'IGNORE'
		foreach($this->map->{$type}['resource_misc'] as $key => $value)
		{
			if(isset($this->vars["resource_$key"]) && 
				(trim($this->vars["resource_$key"]) == $this->messages->text("misc", "ignore")))
			{
				$this->session->delVar("resource_$key");
				continue;
			}
			if(isset($this->vars["resource_$key"]) && trim($this->vars["resource_$key"]) 
			&& !is_numeric(trim($this->vars["resource_$key"])))
				$this->badInput($this->errors->text("inputError", "nan", " (" . 
				$this->messages->text("resources", 
				$this->map->{$type}['resource_misc'][$key]) . ")"), 'stage4');
		}
// if day is set but not month, remove day from session
		if($this->session->getVar("resource_miscField2") && !$this->session->getVar("resource_miscField3"))
			$this->session->delVar("resource_miscField2");
// publicationYear is required
		foreach($this->map->{$type}['resource_year'] as $key => $value)
		{
			if(!isset($this->vars["resource_$key"]) || !trim($this->vars["resource_$key"]) 
			|| !is_numeric(trim($this->vars["resource_$key"])))
				$this->badInput($this->errors->text("inputError", "invalid", " (" . 
				$this->messages->text("resources", 
				$this->map->{$type}['resource_year'][$key]) . ")"), 'stage4');
		}
	}
// Error handling.  Everything sent back to function resource which prints error message.
// Reset $this->vars['method'] for resource to parse function correctly.
// If $this->session->getVar("resource_fullTitle"), we are editing.
	function badInput($error, $method = FALSE)
	{
		include_once("core/html/CLOSE.php");
		if(($method == 'stage2') || ($method == 'stage1a'))
		{
			$this->parentObject->vars['resource_type'] = $this->session->getVar("resource_type");
			$this->parentObject->vars['resource_title'] = $this->session->getVar("resource_title");
			$this->parentObject->vars['resource_subtitle'] = $this->session->getVar("resource_subtitle");
			$this->parentObject->vars['resource_fullTitle'] = $this->session->getVar("resource_fullTitle");
		}
		else if($method == 'stage3') // converting
		{
			include_once("core/resource/RESOURCEEDIT.php");
			$this->parentObject = new RESOURCEEDIT($this->db, $this->vars);
			$this->parentObject->vars['resource_editError'] = TRUE;
			$this->parentObject->vars['resource_type'] = FALSE;
			$this->parentObject->vars['resource_typeConvert'] = $this->session->getVar("resource_typeConvert");
			$this->parentObject->vars['resource_title'] = $this->session->getVar("resource_title");
			$this->parentObject->vars['resource_subtitle'] = $this->session->getVar("resource_subtitle");
			$this->parentObject->vars['resource_fullTitle'] = $this->session->getVar("resource_fullTitle");
		}
		else if(($method == 'stage4') && $this->session->getVar("resource_fullTitle")) // editing
		{
			include_once("core/resource/RESOURCEEDIT.php");
			$this->parentObject = new RESOURCEEDIT($this->db, $this->vars);
			$this->parentObject->vars['resource_editError'] = TRUE;
			$this->parentObject->vars['resource_type'] = $this->session->getVar("resource_type");
			$this->parentObject->vars['resource_typeConvert'] = $this->session->getVar("resource_typeConvert");
			$this->parentObject->vars['resource_title'] = $this->session->getVar("resource_title");
			$this->parentObject->vars['resource_subtitle'] = $this->session->getVar("resource_subtitle");
			$this->parentObject->vars['resource_fullTitle'] = $this->session->getVar("resource_fullTitle");
			$method = 'stage3';
		}
		else if($method == 'stage4') // new resource
		{
			include_once("core/resource/RESOURCENEW.php");
			$this->parentObject = new RESOURCENEW($this->db, $this->vars);
			$this->parentObject->vars['resource_title'] = $this->session->getVar("resource_title");
			$this->parentObject->vars['resource_subtitle'] = $this->session->getVar("resource_subtitle");
			$method = 'stage3';
		}
		if($method)
			$this->parentObject->vars['method'] = $method;
		else if(array_key_exists('method', $this->parentObject->vars))
			unset($this->parentObject->vars['method']);
		if($this->session->issetVar('resource_resourceId'))
			$this->parentObject->vars['id'] = $this->session->getVar('resource_resourceId');
		new CLOSE($this->db, $this->parentObject->resource($error));
	}
// Remove empty values from $this->vars.
// Additionally, remove any previous session variable of that name if the input is empty or FALSE
	function triage()
	{
		$allInput = $this->vars;
		foreach($allInput as $key => $value)
		{
			if(!is_array($value) && !trim($value))
			{
				unset($this->vars[$key]);
				$this->session->delVar($key);
			}
		}
		$sessionVars = $temp = $this->session->getArray('resource');
		if(!isset($sessionVars) || !$sessionVars)
			$sessionVars = array();
		return $sessionVars;
	}
// write input to session
	function writeSession()
	{
//print_r($this->vars); print "<P>";
// Converting resource type?
		if($this->session->getVar("resource_typeConvert"))
			$this->vars['resource_type'] = $this->session->getVar("resource_typeConvert");
// Write all input with 'resource_' prefix to session
		foreach($this->vars as $key => $value)
		{
			if(preg_match("/^resource_/", $key))
			{
// Is this a multiple select box input?  If so, multiple choices are written to session as 
// comma-delimited string (no spaces).
				if(is_array($value))
					$value = implode(",", $value);
				$temp[$key] = trim($value);
			}
		}
		if(isset($temp))
			$this->session->writeArray($temp);
//print_r($temp); print "<P>";
	}
}
?>
